(function($){    
    var _notificationCache = {};    //缓存消息对象.    
    var _isTitleScroll = false;  //消息来时，是否标题滚动提示.            
    var _lastNotification = null;   //最后一条通知.     
    var _autoClose = false; //是否自动关闭.
    var _onlyShowOneNotification = true;
    
    var _isShowing = false;
    
    var _taskPtr = null;
    
    /**
     * @class WebNotification
     * 浏览器通知管理类.
     * @constructor 
     */
    function _WebNotification(){}
    
    var $button = $('<button class="h">test</button>');   
    $(function(){
        $button.click(function(){        
            Notification.requestPermission(function(status) {});
        });
        $button.appendTo('body');
    });
            
    /**
     * 显示一个消息通知.
     * @param {Option} topic
     */
    _WebNotification.show = function(config){        
        if(_taskPtr ){
            window.clearTimeout(_taskPtr);
        }       
        _taskPtr = (function(){
            if(_onlyShowOneNotification){
                _WebNotification.hideLastNotification();
            }                                    
            //消息通知ID.
            var msgID = config['id'];
            
            if(msgID && !_notificationCache[msgID]){
                _notificationCache[msgID] = [];
            }
            
            _WebNotification.scrollPageTitle(config['title']);                
            
            var newNotification = new Notification(
                config['title'], 
                { 
                    icon: config['icon'] || ujs.getRes('images/common128/system.png'), 
                    body: config['msg'] 
                }
            ); 
            
            _lastNotification = newNotification;  
             
            newNotification.onclick = function(){
                //sessionList.startSession(msgID);
                Type.isFunction(window.focus) && window.focus(); 
                window.setTimeout(function(){
                    $('#sessionListTab .sessionListItem.current').trigger('click');
                }, 10);          
            };
            if(newNotification.show) {
                newNotification.show();
            }         
            console.log('show tip');
            
            if(_autoClose){   
                //5s后自动关闭通知框.
                newNotification.close.defer(1000 * 5, newNotification);
            }                    
            //缓存消息通知对象.
            if(msgID){
                _notificationCache[msgID].push(newNotification);
            }
            
            _WebNotification.playSound();
            
        }).defer(200);
             
        return this;
    };
    
    /**
     * 
     * @param {String} chatGroupID
     */
    _WebNotification.hide = function(chatGroupID){        
        if(_isTitleScroll){
            ujs.browser.titleScroller.restore();
        }
        if(chatGroupID){
            var notificationArr = _notificationCache[chatGroupID];
            if(notificationArr && notificationArr.length){
                for(var i=0; i<notificationArr.length; i++){
                    notificationArr[i].close();
                }
            }
        }
        return this;
    };
    
    /**
     * 隐藏最后一项通知. 
     */
    _WebNotification.hideLastNotification = function(){
        if(_lastNotification && Type.isFunction(_lastNotification.close)){
            _lastNotification.close();
            _lastNotification = null;
            console.log('hide tip--------');
        }
    };
    
    /**
     * 播放音效. 
     */
    _WebNotification.playSound = function(){
        var _notificationSound = new Audio(ujs.getRes("audio/sms_received.wav"));  
        return function(){      
            if(window.navigator.userAgent.indexOf('Windows') > -1){
                _notificationSound.play();
            }
        };
    };

    /**
     * 页面标题滚动. 
     */
    _WebNotification.scrollPageTitle = function(title){
        if(_isTitleScroll){
            ujs.browser.titleScroller.scroll(lan('app.im.chat.msgTip', title));
        }
    };
    
    /**
     * 判断当前是否有通知显示. 
     */
    _WebNotification.isNotificationShowing = function(title){
        if(_lastNotification){
            return true;
        }
        return false;
    };

    /**
     * 提醒用户需要启用Notification配置. 
     */
    _WebNotification.showEnableNotificationTip = function(){
        if(!(Notification.permission == 'granted')){            
            (function(){
                ujs.ui.Dialog.get({
                    title : 'Enable Desktop Notifications',
                    closable : false,
                    resizable : false,
                    toolbar : false,
                    bodyStyle : 'text-align:center',
                    html : [                                    
                        '<div style="text-align: left;line-height: 20px;margin-bottom: 10px;zoom:1.2;">',
                            '<h2 style="margin-bottom: 8px;font-weight: bold;">Dear customer,</h2>',
                            '<div style="margin-bottom:8px;">This guide is to help you use desktop notifications.</div>',
                            'After you click "Okay" button, you will see a message on top ',
                            '"Allow AcuCom to show desktop notifications?", ',
                            'please ensure that you click "Allow" button.',
                        '</div>',
                        '<button style="background: #B9B9B9;padding: 5px 10px;border-radius: 5px;letter-spacing: 1px;font-weight: bold;" onclick=\'$("button.h").trigger("click");ujs.ui.Dialog.current.close()\'>Okay</button>'
                    ].join(''),
                    width : 450,
                    height:242,    
                });
           }).defer();
        }
    };

    ujs.define('WebNotification', 'ujs.browser', function(){
        return _WebNotification;
    });    
})($);